/*
 * @Author: orc
 * @we_chat: orc_develop
 * @qq群: 790373986
 * @LastEditors: orc
 * @Description: 
 * @Date: 2019-03-20 10:30:21
 * @LastEditTime: 2019-03-25 22:11:20
 */

import orc from "../orc";

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {
   
    @property(cc.Node)
    auth_node: cc.Node = null;

    // LIFE-CYCLE CALLBACKS:

    /**
     * 必须加入await，让所有的配置都读取成功和赋值后，再进去下一步。
     * 否则其他的子模块onload有初始值，将会为undefind
     */
    async onLoad () {
        this.config_init(); //配置初始化：用于是否打印信息、服务器测试/正式地址（云开发的话，没用）        
        await this.game_init();   //游戏初始化:用于1.读取本地数据库 2.判断是否微信授权 3.初始化完毕，则是否开启授权按钮
        await this.json_init();   //读取相应的json文件
        
        if (window["cocosAnalytics"] !== 'undefined'){
            console.log('cocosAnalytics yes');
           
            // window["cocosAnalytics"].CACustomEvent.onStarted("事件ID1", {
            //     "关卡":"关卡"
            // });
        }
    }

    async start () {
         console.log('size:',cc.view.getFrameSize());  
    }

    /**
     * 配置初始化：用于是否打印信息、服务器测试/正式地址（云开发的话，没用）
     */
    config_init(){  
        if(orc.game_config.DEBUG === true){
            orc.game_config.HTTP_URL = orc.game_config.HTTP_TEST_URL; //配置为测试服务器地址            
        }
        else{
            orc.game_config.HTTP_URL = orc.game_config.HTTP_ONLINE_URL; //配置为正式服务器地址
            
        }  
        if(orc.game_config.console === false)
        {
            //把console.log屏蔽掉
            console.log = (function(oriLogFunc){
                return function()
                {
                    oriLogFunc.apply(null);
                }
            });
        }        
    }

    /**
     * 读取相应的json文件
     */
    async json_init(){
        let json = await orc.load_json.load_json('nickname.json');//读取昵称的json文件，用于ai昵称生成
        console.log(json);
    }

    /**
     * 游戏初始化:
     * 1.跟服务端通信，读取用户表，判断是否为新老用户,是否需要开启微信授权 
     * 
     * 2.游戏数据的新用户初始化/老用户读取
    */
   async game_init(){ 
        return new Promise(async (reslove)=>{
            if(cc.sys.platform == cc.sys.WECHAT_GAME)
            {            
                orc.game_config.Platform = "wx"; 
                console.log("orc.local_data:",orc.game_config.Platform,orc.local_data);
                orc.local_data.load_local_data();//读取本地数据

                //获取微信的code
                let res_code = await orc.platform_manager.platform.get_code();
                let body ={};
                body['code'] = res_code.code; 
                body['platform'] = 'wx';
                //获取用户信息
                let res_login:any = await orc.net_http.http_post(orc.url_config.http_login,body);       //验证微信信息
                
                if(res_login == 'timeout')
                {
                    console.error('net_http get_openid() timeout');
                    return;
                } 
                console.log('res_login:',res_login);
                if(res_login.code == 0)
                {
                    if(res_login.data.userinfo.nickname == undefined || res_login.data.userinfo.nickname == '' || res_login.data.userinfo.nickname == null)
                    {
                        //新用户(未授权的用户)
                        console.log('新用户（未授权，授权过都当做老用户）');
                        this.auth_node.active = true;
                    }
                    else
                    {
                        console.log('老用户');                
                        if(orc.local_data.user_name != res_login.data.userinfo.nickname)
                        {
                            //判断用户是否删除游戏，而进入游戏的，这样不需再次授权
                            orc.local_data.user_name = res_login.data.userinfo.nickname;
                            orc.local_data.user_image = res_login.data.userinfo.thumb;
                            await orc.local_data.save_local_data();
                        }                        
                        this.auth_node.active = false;
                    }                
                    orc.memory_data.user_data = res_login.data.userinfo;        
                }  
                    
            } 
            else if(cc.sys.platform == cc.sys.DESKTOP_BROWSER || cc.sys.platform == cc.sys.MOBILE_BROWSER)
            {
                orc.game_config.Platform = "other";
            
                console.log("orc.local_data:",orc.game_config.Platform,orc.local_data);
                orc.local_data.load_local_data();
                
                let body:any = {};
                body['code'] = 1; 
                body['platform'] = orc.game_config.Platform;
                body['jsonp'] = 1;
            
                let body_form = orc.utils.json_to_formdata(body);

                //获取用户信息
                let res_login:any = await orc.net_http.http_post(orc.url_config.http_login,body_form);       //验证微信信息
                
                if(res_login == 'timeout')
                {
                    console.error('net_http get_openid() timeout');
                    return;
                } 
                console.log('res_login:',res_login);
                if(res_login.code == 0)
                {
                    if(orc.local_data.user_name != res_login.data.userinfo.nickname)
                    {
                        //判断用户是否删除游戏，而进入游戏的，这样不需再次授权
                        orc.local_data.user_name = res_login.data.userinfo.nickname;
                        orc.local_data.user_image = res_login.data.userinfo.thumb;
                        await orc.local_data.save_local_data();
                    } 
                    orc.memory_data.user_data = res_login.data.userinfo;
                }
                else
                {
                    orc.memory_data.user_data.money = 100;
                }            
            } 
            
            reslove('ok');
        })
        
   }

   
}
